package com.nfzm.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.nfzm.entity.ArticleVO;
import com.nfzm.entity.NfzmArticlePic;
import com.nfzm.entity.NfzmTerm;
import com.nfzm.service.NfzmArticlePicService;
import com.nfzm.service.NfzmTermService;
import com.nfzm.service.impl.NfzmArticlePicServiceImpl;
import com.nfzm.service.impl.NfzmArticleServiceImpl;
import com.nfzm.tools.HttpTool;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import com.nfzm.service.NfzmArticleService;
import com.nfzm.entity.NfzmArticle;

import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * NfzmArticle的路由接口服务
 * 
 * @author 
 *
 */
@RestController
@Slf4j
public class NfzmArticleController {

	/** NfzmArticleService服务 */
	@Autowired
	private NfzmArticleService nfzmArticleService;

	@Autowired
	private NfzmArticlePicService picService;

	@Autowired
	private NfzmTermService termService;

	@RequestMapping("/data")
	public String data(NfzmTerm term){

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		JSONObject result = new JSONObject();

		JSONObject data = null;

		JSONArray jsonArray = new JSONArray();

		List<NfzmTerm> termList = termService.find(term);

		for(NfzmTerm resultTerm:termList){
			Integer page = 0;
			String termId = resultTerm.getTermId();
			do{
				try{
					String url = "https://www.infzm.com/contents?term_id="+termId+"&page="+page+"&format=json";
					result = HttpTool.get(url);
					page++;
					log.info("第几页"+page);
					jsonArray.clear();
					data = result.getJSONObject("data");
					if(null!=data){
						jsonArray = data.getJSONArray("contents");
						log.info("返回数据大小"+jsonArray.size());
						List<NfzmArticle> articleList = new ArrayList<>();
						for(Object ele:jsonArray){
							JSONObject jsonObject = (JSONObject) ele;
							String id = jsonObject.getString("id");
							String subject = jsonObject.getString("subject");
							String introText = jsonObject.getString("introtext");
							Date date = formatter.parse(jsonObject.getString("publish_time"));

							NfzmArticle article = new NfzmArticle();
							article.setId(id);
							article.setDate(date);
							article.setIntroText(introText);
							article.setTitle(subject);
							article.setTermId(termId);
							article.setInsertTime(new Date());

							try{
								nfzmArticleService.saveNotNull(article);
							}catch (Exception e){
								log.error("文章插入报错"+e.getMessage());
							}


							JSONArray pics = jsonObject.getJSONArray("covers");
							if(null!=pics){
								List<NfzmArticlePic> picList = new ArrayList<>();
								for(int i=0;i<pics.size();i++){
									JSONObject picJson =(JSONObject) pics.get(i);
									NfzmArticlePic pic = new NfzmArticlePic();
									String picUrl = picJson.getString("file_path");
									int width = picJson.getIntValue("media_width");
									int height = picJson.getIntValue("media_height");
									int length = picJson.getIntValue("media_length");
									pic.setArticleId(id);
									pic.setSort(i);
									pic.setWidth(width);
									pic.setHeight(height);
									pic.setLength(length);
									pic.setPicUrl(picUrl);
									pic.setInsertTime(new Date());
									try{
										picService.saveNotNull(pic);
									}catch (Exception e){
										log.error("图片插入报错"+e.getMessage());
									}

								}

							}

						}

					}

				}catch (Exception e){
					log.error("出错了",e);
				}


			}while (jsonArray.size()>0);
		}

		log.info("end------------------------------");


		return "0";
	}

	@RequestMapping("/data2")
	public String data2(NfzmTerm term){

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		JSONObject result = new JSONObject();

		JSONObject data = null;

		JSONArray jsonArray = new JSONArray();


			Integer page = 0;
			String termId ="1";
			do{
				try{
					String url = "https://www.infzm.com/contents?term_id="+termId+"&page="+page+"&format=json";
					result = HttpTool.get(url);
					page++;
					log.info("第几页"+page);
					jsonArray.clear();
					data = result.getJSONObject("data");
					if(null!=data){
						jsonArray = data.getJSONArray("contents");
						log.info("返回数据大小"+jsonArray.size());
						List<NfzmArticle> articleList = new ArrayList<>();
						for(Object ele:jsonArray){
							JSONObject jsonObject = (JSONObject) ele;
							String id = jsonObject.getString("id");
							String subject = jsonObject.getString("subject");
							String introText = jsonObject.getString("introtext");
							Date date = formatter.parse(jsonObject.getString("publish_time"));

							NfzmArticle article = new NfzmArticle();
							article.setId(id);
							article.setDate(date);
							article.setIntroText(introText);
							article.setTitle(subject);
							article.setTermId(termId);
							article.setInsertTime(new Date());
							article.setIsRecommend("1");


							try{
								nfzmArticleService.saveNotNull(article);
								JSONArray pics = jsonObject.getJSONArray("covers");
								if(null!=pics){
									List<NfzmArticlePic> picList = new ArrayList<>();
									for(int i=0;i<pics.size();i++){
										JSONObject picJson =(JSONObject) pics.get(i);
										NfzmArticlePic pic = new NfzmArticlePic();
										String picUrl = picJson.getString("file_path");
										int width = picJson.getIntValue("media_width");
										int height = picJson.getIntValue("media_height");
										int length = picJson.getIntValue("media_length");
										pic.setArticleId(id);
										pic.setSort(i);
										pic.setWidth(width);
										pic.setHeight(height);
										pic.setLength(length);
										pic.setPicUrl(picUrl);
										pic.setInsertTime(new Date());
										try{
											picService.saveNotNull(pic);
										}catch (Exception e){
											log.error("图片插入报错"+e.getMessage());
										}

									}

								}
							}catch (DuplicateKeyException e){
								log.error("文章已存在"+e.getMessage());
								nfzmArticleService.updateNotNullById(article);
							}catch (Exception e2){
								log.error("文章插入报错"+e2.getMessage());
							}


						}

					}

				}catch (Exception e){
					log.error("出错了",e);
				}


			}while (jsonArray.size()>0);


		log.info("end------------------------------");


		return "0";
	}

	/**
	 * 查询所有NfzmArticle数据的方法
	 * @param value
	 * @return
	 */
	@GetMapping(value = "/list", produces = {"application/json;charset=UTF-8"})
	public List<NfzmArticle> list(ArticleVO value) {
		if(null==value.getTermId() && null==value.getName()){
			value.setTermId("129");
		}
		return nfzmArticleService.findWithPics(value);
	}

	@GetMapping("/setContent")
	public int setContent(ArticleVO value){


		List<NfzmArticle> articleList = new ArrayList<>();
		List list = new ArrayList();
		int sum = 0;
		value.setContent("null");
		if(0==value.getPageSize()){
			value.setPageSize(10);
			value.setPage(1);
		}

		do{
			try{
				articleList = nfzmArticleService.dealData(value);
				log.info("返回条数"+articleList.size());
				int page = value.getPage();
				log.info("处理页数"+page);
				page++;
				int smallNum = 0;
				//value.setPage(page);
				for(NfzmArticle article:articleList){
					int result = 0;
					try{
						 result = nfzmArticleService.setContent(article);
					}catch (Exception e){
						log.info("更新报错"+e.getMessage());
					}
					if(0==result){
						list.add(article.getId());
					}
					sum+=result;
					smallNum+=result;
				}
				log.info("本次循环处理成功"+smallNum);
			}catch (Exception e){
				log.error("接口层报错",e);
			}


		}while (articleList.size()>0);

		log.info("结束总共成功"+sum);
		System.out.println(list);
		return sum;
	}

	@GetMapping("/dealData")
	public int dealData(ArticleVO value){


		List<NfzmArticle> articleList = new ArrayList<>();
		List list = new ArrayList();
		int sum = 0;
		if(0==value.getPageSize()){
			value.setPageSize(10);
			value.setPage(1);
		}

		value.setNextId("1");

		do{
			try{
				articleList = nfzmArticleService.dealData(value);
				log.info("返回条数"+articleList.size());
				if(articleList.size()==0){
					log.info("结束了");
				}
				int page = value.getPage();
				log.info("处理页数"+page);
				page++;
				int smallNum = 0;
				//value.setPage(page);
				for(NfzmArticle article:articleList){
					int result = 0;
					try{
						result = nfzmArticleService.setContent(article);
					}catch (Exception e){
						log.info("更新报错"+e.getMessage());
					}
					if(0==result){
						list.add(article.getId());
					}
					sum+=result;
					smallNum+=result;
				}
				log.info("本次循环处理成功"+smallNum);
			}catch (Exception e){
				log.error("接口层报错",e);
			}


		}while (articleList.size()>0);

		log.info("结束总共成功"+sum);
		System.out.println(list);
		return sum;
	}
	/**
	 * 通过id查询NfzmArticle数据的方法
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/NfzmArticle/{id}", produces = {"application/json;charset=UTF-8"})
	public NfzmArticle findOne(@PathVariable(name="id") String id) {
		return nfzmArticleService.findOne(id);
	}

	@GetMapping(value = "/queryOthers/{id}", produces = {"application/json;charset=UTF-8"})
	public NfzmArticle queryOthers(@PathVariable(name="id") String id) {
		return nfzmArticleService.findWithOthers(id);
	}
	
	/**
	 * 插入NfzmArticle属性不为空的数据方法
	 * @param
	 * @return
	 */
	@PostMapping(value = "/NfzmArticle", produces = {"application/json;charset=UTF-8"})
	public int save(NfzmArticle value) {
		return nfzmArticleService.saveNotNull(value);
	}
	
	/**
	 * 更新NfzmArticle属性不为空的数据方法
	 * @param
	 * @return
	 */
	@PutMapping(value = "/NfzmArticle", produces = {"application/json;charset=UTF-8"})
	public int update(NfzmArticle value) {
		return nfzmArticleService.updateNotNullById(value);
	}
	
	/**
	 * 通过id删除NfzmArticle数据方法
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/NfzmArticle/{id}", produces = {"application/json;charset=UTF-8"})
	public int delete(@PathVariable(name="id") String id) {
		return nfzmArticleService.deleteById(id);
	}


	@RequestMapping("/terms")
	public int insertTerms(){

		String url = "https://www.infzm.com/termsf";
		Document document = null;
		int sum =0;

		try {
			document = Jsoup.connect(url).get();
			//Elements elements = document.getElementsByClass("nfzm-term-list__item");
			Element navi = document.getElementsByClass("nfzm-navi").get(0);
			Elements elements = navi.select("li");
			for(Element element:elements){
				/*String elemenntUrl = element.select("a").get(0).attr("href");
				int begin = elemenntUrl.indexOf("=");
				int end = elemenntUrl.indexOf("&");
				String id = elemenntUrl.substring(begin+1,end);
				String picUrl = element.select("img").get(0).attr("src");
				String name = element.select("footer").get(0).text();*/
				String name =	element.child(0).text();
				String detailUrl = element.child(0).attr("href");
				int begin = detailUrl.indexOf("=");
				String id = detailUrl.substring(begin+1,detailUrl.length());

				NfzmTerm term = new NfzmTerm();
				term.setTermName(name);
				term.setTermId(id);
				term.setIsMajor(1);

				termService.saveNotNull(term);
				sum++;
			}


		}catch (Exception e){
			log.error("",e);
		}

		return sum;
	}
}
